import { ReactElement, useState, useEffect } from 'react'
import style from './index.module.less'
import { Table } from 'antd'
import { getColumn } from './util'
import EditModal from './components/EditModal/Index'
import { ConfigSchema, getListRequest } from './ajax'
import { awaitWrap } from '@js/tool'

async function initData (setDataSource: (v: ConfigSchema[]) => void, setLoading: (v: boolean) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getListRequest())
  setLoading(false)
  if (e === null && d instanceof Array) {
    setDataSource(d)
  }
}

function Main (): ReactElement {
  const [visible, setVisible] = useState(false)
  const [modifyData, setModifyData] = useState<ConfigSchema | null>(null)
  const [dataSource, setDataSource] = useState<ConfigSchema[]>([])
  const [loading, setLoading] = useState(false)
  function initFn (): void { initData(setDataSource, setLoading).catch(e => console.error(e)) }
  useEffect(() => {
    initFn()
  }, [])
  return (
    <div className={style.container}>
      <EditModal visible={visible} hide={() => { setModifyData(null); setVisible(false) }} data={modifyData} refreshData={initFn} />
      <div className={style.body}>
        <div className={style.inner}>
          <div className={style['title-line']}>
            <span className={style['title-line-text']}>配置列表</span>
          </div>
          <Table columns={getColumn(setModifyData, setVisible)} loading={loading} dataSource={dataSource} pagination={false} />
        </div>
      </div>
    </div>
  )
}

export default Main
